package com.kdl.webconfig.business;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kdl.webconfig.converter.VOConvert;
import com.kdl.webconfig.vo.PageVO;
import com.kdl.webconfig.entity.News;
import com.kdl.webconfig.enums.NewsStateEnum;
import com.kdl.webconfig.service.INewsDetailService;
import com.kdl.webconfig.service.INewsService;
import com.kdl.webconfig.vo.config.NewsQueryReq;
import com.kdl.webconfig.vo.config.NewsVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author 王成杰
 * @description TODO
 * @date 2022-09-06 上午11:48
 */
@Component
public class NewsBusiness {

    @Autowired
    INewsService iNewsService;

    @Autowired
    INewsDetailService iNewsDetailService;


    public PageVO<NewsVO> page(NewsQueryReq newsQueryReq) {
        Page<News> page = iNewsService.queryPage(newsQueryReq);
        return buildNewsPage(page);
    }

    private PageVO<NewsVO> buildNewsPage(Page<News> page) {
        PageVO<NewsVO> newsVOPageVO = new PageVO<>();
        if(Objects.nonNull(page)) {
            newsVOPageVO.setCurrentPage(page.getCurrent());
            newsVOPageVO.setPageSize(page.getSize());
            newsVOPageVO.setTotalPages(page.getPages());
            newsVOPageVO.setTotalSize(page.getTotal());
            newsVOPageVO.setList(VOConvert.parseNewsVosByPojos(page.getRecords()));
        }
        return newsVOPageVO;
    }


    /**
     * 新闻更新或保存
     * @param newsVO
     * @return
     */
    public Boolean saveOrUpdate(NewsVO newsVO) {
        News news = buildNewsByVO(newsVO);
        return iNewsService.saveOrUpdate(news);
    }

    private News buildNewsByVO(NewsVO newsVO) {
        if(Objects.isNull(newsVO)){
            return null;
        }
        News news = new News();
        news.setId(newsVO.getId());
        news.setTitle(newsVO.getTitle());
        news.setComment(newsVO.getComment());
        news.setLinkUrl(newsVO.getLinkUrl());
        news.setState(newsVO.getState());
        if(newsVO.getState().equals(NewsStateEnum.publish.getCode())) {
            news.setPublishTime(new Date());
        }
        news.setPicUrl(newsVO.getPicUrl());
        return news;
    }

    /**
     *  删除问题
     * @param id
     * @return
     */
    public Boolean deleteById(Integer id) {
        boolean b = iNewsService.removeById(id);
        if(b){
            iNewsDetailService.deleteByNewsId(id);
        }
        return b;
    }

    /**
     * 新闻详情
     * @param id
     * @return
     */
    public NewsVO detail(Integer id) {
        News byId = iNewsService.getById(id);
        NewsVO newsVO = VOConvert.parseNewsVOByPojo(byId);
        return newsVO;
    }
}
